<?php

class EvaluationConstraintReviewsController extends AppController {

    var $name = 'EvaluationConstraintReviews';

    public function index($evaluation_constraint_id) {
        $this->layout = "ajax";
        $this->EvaluationConstraintReview->EvaluationConstraint->recursive = -1;
        $this->set('constraint', $this->EvaluationConstraintReview->EvaluationConstraint->find("first", array("conditions" => array("EvaluationConstraint.id" => $evaluation_constraint_id), "fields" => array("EvaluationConstraint.*"))));
        $this->set('revisiones', $this->EvaluationConstraintReview->find('all', array('recursive' => 0, 'conditions' => array('EvaluationConstraintReview.evaluation_constraint_id' => $evaluation_constraint_id), 'order' => array('EvaluationConstraintReview.id DESC'), 'fields' => array('EvaluationConstraintReview.comentario', 'EvaluationConstraintReview.id', 'EvaluationConstraintReview.fecha', 'User.nombre', 'User.primer_apellido', 'User.segundo_apellido'))));
    }

    public function add($evaluation_constraint_id) {
        $this->set('evaluation_constraint_id', $evaluation_constraint_id);

        if (!empty($this->data)) {
            $this->data['EvaluationConstraintReview']['user_id'] = $this->Auth->user('id');

            if (empty($this->data['EvaluationConstraintReview']['fecha']) or $this->data['EvaluationConstraintReview']['fecha'] == "") {
                date_default_timezone_set("America/Bogota");
                $this->data['EvaluationConstraintReview']['fecha'] = date("Y-m-d-h-i-s");
            }

            if ($this->EvaluationConstraintReview->saveAll($this->data)) {
                $this->Session->setFlash('Registro guardado correctamente');
                $this->redirect(array('controller' => 'EvaluationConstraintReviews', 'action' => 'index', $evaluation_constraint_id));
            } else {
                $this->Session->setFlash('Error guardando datos');
            }
        }
    }

    public function edit($id) {
        $this->EvaluationConstraintReview->recursive = -1;
        $evaluation_constraint_id = $this->EvaluationConstraintReview->field('EvaluationConstraintReview.evaluation_constraint_id', array('EvaluationConstraintReview.id' => $id));
        $user_id = $this->EvaluationConstraintReview->field('EvaluationConstraintReview.user_id', array('EvaluationConstraintReview.id' => $id));
        if (!empty($this->data)) {
            if (empty($this->data['EvaluationConstraintReview']['fecha']) or $this->data['EvaluationConstraintReview']['fecha'] == "") {
                date_default_timezone_set("America/Bogota");
                $this->data['EvaluationConstraintReview']['fecha'] = date("Y-m-d-h-i-s");
            }

            if ($this->EvaluationConstraintReview->saveAll($this->data)) {
                $this->Session->setFlash('Registro guardado correctamente');
                $this->redirect(array('controller' => 'EvaluationConstraintReviews', 'action' => 'index', $this->data['EvaluationConstraintReview']['evaluation_constraint_id']));
            } else {
                $this->Session->setFlash('Error guardando datos');
            }
        } else {
            if ($user_id == $this->Auth->user('id')) {
                $this->EvaluationConstraintReview->recursive = -1;
                $this->data = $this->EvaluationConstraintReview->find('first', array('conditions' => array('EvaluationConstraintReview.id' => $id), 'fields' => array('EvaluationConstraintReview.*')));
            } else {
                $this->Session->setFlash('Este registro fue hecho por otro usuario.', 'flash_custom');
                $this->redirect(array('controller' => 'EvaluationConstraintReviews', 'action' => 'index', $evaluation_constraint_id));
            }
        }
    }

    public function report() {

        $this->layout = 'csv';
        ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
        //create a file
        $filename = "Reporte_seguimiento_condicionamientos_" . date("Y.m.d") . ".csv";
        $csv_file = fopen('php://output', 'w');
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $sql = "SELECT Proyect.codigo, Proyect.id, b.nombre, EvaluationConstraint.descripcion, EvaluationConstraint.calificacion,User.nombre, User.primer_apellido, User.segundo_apellido, EvaluationConstraintReview.comentario, EvaluationConstraintReview.fecha FROM evaluation_constraints EvaluationConstraint
                LEFT JOIN final_evaluations FinalEvaluation ON EvaluationConstraint.final_evaluation_id = FinalEvaluation.id
                LEFT JOIN proyects Proyect ON FinalEvaluation.proyect_id = Proyect.id
                LEFT JOIN evaluation_constraint_reviews EvaluationConstraintReview ON EvaluationConstraintReview.evaluation_constraint_id = EvaluationConstraint.id
                LEFT JOIN users User ON User.id = EvaluationConstraintReview.user_id
                LEFT JOIN constraints b ON b.id = EvaluationConstraint.constraint_id";

        $results = $this->EvaluationConstraintReview->query($sql);

        // The column headings of your .csv file
        $header_row = array("Código proyecto", "Tipo condicionamiento", "Descripción condicionamiento", "Estado", "Usuario", "Comentario", "Fecha");

        $newRow = array();

        foreach ($header_row as $a) {
            $newRow[] = iconv('UTF-8', 'Windows-1252', $a);
        }

        fputcsv($csv_file, $newRow, ';', '"');

        // Each iteration of this while loop will be a row in your .csv file where each field corresponds to the heading of the column
        App::Import('Model', 'FinalEvaluation');
        $evaluacion = new FinalEvaluation();
        $evaluacion->recursive = -1;


        foreach ($results as $result) {
            // Array indexes correspond to the field names in your db table(s)
            $resultado_evaluacion_final = $evaluacion->field('FinalEvaluation.calificacion_elegibilidad_integral', array('FinalEvaluation.proyect_id' => $result['Proyect']['id']), 'FinalEvaluation.id DESC');
            if ($resultado_evaluacion_final == 'Elegible') {
                $row = array(
                    $result['Proyect']['codigo'],
                    $result['b']['nombre'],
                    $result['EvaluationConstraint']['descripcion'],
                    $result['EvaluationConstraint']['calificacion'],
                    $result['User']['nombre'] . " " . $result['User']['primer_apellido'] . " " . $result['User']['segundo_apellido'],
                    $result['EvaluationConstraintReview']['comentario'],
                    $result['EvaluationConstraintReview']['fecha'],
                );

                $newRow = array();

                foreach ($row as $a) {
                    $newRow[] = iconv('UTF-8', 'Windows-1252', $a);
                }

                fputcsv($csv_file, $newRow, ';', '"');
            }
        }

        fclose($csv_file);
    }

    public function delete($id, $evaluation_constraint_id) {
        $this->EvaluationConstraintReview->recursive = -1;
        $user_id = $this->EvaluationConstraintReview->field('user_id', array('EvaluationConstraintReview.id' => $id));
        if ($user_id == $this->Auth->user('id')) {
            if ($this->EvaluationConstraintReview->delete($id)) {
                $this->Session->setFlash('Se elimino con éxito', 'flash_custom');
                $this->redirect(array('controller' => 'EvaluationConstraintReviews', 'action' => 'index', $evaluation_constraint_id));
            }
        } else {
            $this->Session->setFlash('Este registro fue hecho por otro usuario.', 'flash_custom');
            $this->redirect(array('controller' => 'EvaluationConstraintReviews', 'action' => 'index', $evaluation_constraint_id));
        }
    }

}

?>
